Passed
Push — feature/post-covid-application... ( 4340d4...92a3aa )
by Yonathan
08:31 queued 01:05
created

localize.ts ➔ matchValueToModel   A

Complexity

Conditions 2

Size

Total Lines 11
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
cc 2
1
import { localizedField, localizedFieldNonNull } from "../models/app";
2
3
export type Locales = "en" | "fr";
4
type TranslatableKeysNonNull<T> = {
5
  [K in keyof T]: T[K] extends localizedFieldNonNull ? K : never;
6
}[keyof T];
7
type TranslatableKeys<T> = {
8
  [K in keyof T]: T[K] extends localizedField ? K : never;
9
}[keyof T];
10
11
export function localizeField<T>(
12
  locale: Locales,
13
  model: T,
14
  field: TranslatableKeys<T>,
15
): string | null {
16
  if (model[field] !== null) {
17
    if (model[field][locale] === ("" || null || undefined)) {
18
      return locale === "en" ? "TRANSLATION MISSING" : "TRADUCTION MANQUANTE";
19
    }
20
    return model[field][locale];
21
  }
22
  return null;
23
}
24
export function localizeFieldNonNull<T>(
25
  locale: Locales,
26
  model: T,
27
  field: TranslatableKeysNonNull<T>,
28
): string {
29
  // Even though we assume field is non-null... check anyway to avoid crashes.
30
  const value = model[field] ? model[field][locale] : null;
31
  if (value) {
32
    return value;
33
  }
34
  return locale === "en" ? "TRANSLATION MISSING" : "TRADUCTION MANQUANTE";
35
}
36
37
export function getLocale(locale: string): Locales {
38
  if (locale === "en" || locale === "fr") {
39
    return locale;
40
  }
41
  console.log("Warning: unknown locale. Defaulting to en.");
42
  return "en";
43
}
44
45
export function matchValueToModel<T>(
46
  locale: Locales,
47
  field: TranslatableKeys<T>,
48
  value: string,
49
  possibilities: T[],
50
): T | null {
51
  const matching = possibilities.filter(
52
    (model) => localizeField(locale, model, field) === value,
53
  );
54
  return matching.length > 0 ? matching[0] : null;
55
}
56